package com.songyang.client.handler;

import com.songyang.serialize.SerializeFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName NettyServerHanlder
 * @Description 自定义一个handler，需要继承一个netty好的适配器（有很多）
 * 这样的handler才是netty的handler
 * @date 2022/8/3 16:46
 * @Author yanceysong
 * @Version 1.0
 */

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
    }

    /**
     * 当通道就绪时，就会触发该方法
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("ctx：" + ctx);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("client messgae", StandardCharsets.UTF_8));
    }

    /**
     * 当通道有读取时间时触发
     *
     * @param ctx 上下文
     * @param msg 内容
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        System.out.println(SerializeFactory
                .getDecoder().deserialize(req).getData());
        System.out.print("> > ");
    }
}
